/**
 *
 * Pepperstad
 *
 * x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x
 *
 * <b>Concept</b>
 * I want this game to be a cross breed between all my favorite games... If that's even remotely feasible :-)
 * Inspired by the games "Tower Defense", "The Settlers" , "Close Combat", "X-COM" and "Jagged Alliance",
 * this game should feature some of these elements:
 * - defensive positions
 * - economy simulation
 * - real time combat
 * - keeping your citizens fed, safe and happy
 * - soldier management
 * - building management
 * - occupations depending on skills
 *
 *
 * <b>Description</b>
 * Manage guards to defend your village against raiders, ensure stable food supply and maintain
 * infrastructure to keep your inhabitants happy.
 *
 * @author andersand
 * @created 2011, 2014
 *
 */

pepperstad.Game = function () {

    // public members
    this.resourceLoader = null;
    this.structureService = null;
    this.player = null;
    this.enemy = null;
    this.gui = null;
    this.map = null;

    // private members
    var jobService = null,
        config = pepperstad.config,
        self = this,
        story;

    /**
     * Main initialization
     */
    this.init = function (editor) {
        var loader = new pepperstad.ResourceLoader();
        loader.loadResources();
        var bStoryMode = typeof editor == "undefined";
        // todo add a loader screen with progressbar
        $("body").empty().html("<div id=\"playground\"></div><div id=\"log\"></div><div id=\"dialog\"></div><div id=\"dataloader\">~</div>");
        log("initing game");
        this.initPlayground();
        this.initPlayers();
        this.resourceLoader = loader;
        log("game waiting for resources to load ...");
        daemon("loader", 100, function loaderDaemon() {
            if (loader.loadingComplete()) {
                log("all resources loaded");
                self.gui = new pepperstad.GUI({
                    game: self,
                    resourceLoader: loader
                });
                jobService = new pepperstad.JobService({
                    resourceLoader: self.resourceLoader
                });
                var storyConfig = loader.get("story.config");
                var PLAYGROUND_HEIGHT = storyConfig.imageHeight;
                var PLAYGROUND_WIDTH = storyConfig.imageWidth;
                var paper = new Raphael("structures", PLAYGROUND_WIDTH, PLAYGROUND_HEIGHT);

                self.structureService = new pepperstad.StructureService({
                    paper: paper
                });
                self.map = new pepperstad.Map({
                    game: self,
                    editor: editor,
                    paper: paper,
                    structureService: self.structureService,
                    resourceLoader: loader
                });
                self.map.init();
                self.structureService.loadStructures(self.map, loader);
                $.playground().startGame();
                if (bStoryMode) {
                    self.initButtons();
                    self.initStory();
                }
                return false;
            }
            return true;
        });
    };

    this.initButtons = function () {
        var gui = self.gui;
        var lang = self.resourceLoader.get("lang");
        gui.createButton({
            id: "showUnitManagerButton",
            text: lang["AdministrateCitizens"],
            smallText: true,
            clickHandler: function showUnitManagerHandler() {
                gui.showUnitManager();
            }
        });
        gui.createSpacer();
        gui.createButton({
            id: "gotoEditorButton",
            text: "Editor",
            smallText: false,
            clickHandler: function showUnitManagerHandler() {
                window.location.href = config.contextRoot + "editor.html";
            }
        });
        gui.createLabel({
            text: "Version " + config.version
        });
    };

    this.startGame = function () {
        /**
         * Main daemon
         */
        daemon("heartbeat", 50, function heartbeat() {
            return true;
        });
    };

    /**
     * GameQuery stuff
     */
    this.initPlayground = function () {
        var PLAYGROUND_HEIGHT = config.playgroundHeight;
        var PLAYGROUND_WIDTH = config.playgroundWidth;
        $("#playground").playground({
            keyTracker: true,
            height: PLAYGROUND_HEIGHT,
            width: PLAYGROUND_WIDTH
        })
            .addGroup("background", {
                width: PLAYGROUND_WIDTH,
                height: PLAYGROUND_HEIGHT
            }).end()
            .addGroup("structures", {
                width: PLAYGROUND_WIDTH,
                height: PLAYGROUND_HEIGHT
            }).end()
            .addGroup("player", {
                width: PLAYGROUND_WIDTH,
                height: PLAYGROUND_HEIGHT
            }).end()
            .addGroup("enemy", {
                width: PLAYGROUND_WIDTH,
                height: PLAYGROUND_HEIGHT
            });
        var bgAnimation = new $.gameQuery.Animation({
            imageURL: "res/stories/" + config.story + "/" + config.mapFilename
        });
        $("#background").addSprite("background1", {
            animation: bgAnimation,
            width: PLAYGROUND_WIDTH,
            height: PLAYGROUND_HEIGHT
        });
    };

    this.initPlayers = function () {
        this.player = new pepperstad.Player();
        this.enemy = new pepperstad.Enemy();
    };

    this.initStory = function () {
        var storyJSON = this.resourceLoader.get("story");
        var generator = new pepperstad.Generator({
            resourceLoader: this.resourceLoader
        });
        var inhabitants = generator.generatePeople(storyJSON.playerPeople.generationDefinition);
        var raiders = generator.generatePeople(storyJSON.enemyPeople.generationDefinition);

        story = new pepperstad.Story({
            text: storyJSON.text,
            title: storyJSON.title,
            playerPeople: inhabitants,
            enemyPeople: raiders,
            roamingJobs: storyJSON.roamingJobs
        });
        story.apply(this);

        jobService.generateVacantJobs(story, self.structureService.structures);
        jobService.assignJobs(story.playerPeople);

        this.gui.showStoryDialog(story);
    };
};

/**
 * Story represents a change to the game, with a textual story and may include
 *  - player units
 *  - enemy units
 *
 * Calling apply() should add any units to the players.
 */
pepperstad.Story = function (opts) {

    this.text = opts.text;
    this.title = opts.title;
    this.playerPeople = opts.playerPeople;
    this.enemyPeople = opts.enemyPeople;
    this.roamingJobs = opts.roamingJobs;

    this.apply = function (game) {
        game.player.addPeople(this.playerPeople);
        game.enemy.addPeople(this.enemyPeople);
    };
};

pepperstad.Player = function () {

    this.people = [];

    var self = this;

    this.addPeople = function (aPeople) {
        _.each(aPeople, function (person) {
            self.people.push(person);
        });
    };
};

pepperstad.Enemy = function () {

    this.ai = function () {
        // <spawn foes> (set initial destination, or wait for group)
        // group may <build fortifications> or charge towards a destination
        //  if a leader is present and the group is large enough -> strategic point (weak spot/infrastructure building)
        //  else -> nearest building
    };
};
pepperstad.Enemy.prototype = new pepperstad.Player();
pepperstad.Enemy.prototype.constructor = pepperstad.Enemy;



